package com.automation.selenium;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import jxl.Workbook;
import jxl.WorkbookSettings;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ExecuteKeywordScript extends BaseClass {

  TestDetailedReport tdrObj = new TestDetailedReport();
  TestSummaryReport tsrObj = new TestSummaryReport();
  ObjectRepository orObj = new ObjectRepository();
  KeywordRelatedFunctions krfObj = new KeywordRelatedFunctions();
  IfCondition ifcObj = new IfCondition();
  FindElement fEObj = new FindElement();
  ScreenShot ssObj = new ScreenShot();
  StoreCheck scObj = new StoreCheck();
  RobotActions raObj = new RobotActions();
  DateTimeFunctions dtfObj = new DateTimeFunctions();
  CustomExceptionMessages cemObj = new CustomExceptionMessages();
  DataTable dtObj = new DataTable();
  CheckWindowPresence cwpObj = new CheckWindowPresence();
  WaitForElement wfeObj = new WaitForElement();
  AutoGenerateComments agcObj = new AutoGenerateComments();
  MiscFunctions mfObj = new MiscFunctions();
  DataBase dbObj = new DataBase();
  MobileGesturesAppium mgaObj = new MobileGesturesAppium();
  MobileGesturesSelendroid mgsObj = new MobileGesturesSelendroid();


  public void ExecKeywordScript(String scriptName, String TestScript, String ObjectRepository,
      String ScriptORName) throws Exception {
    // Report header
    cur_dt = new Date();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    String strTimeStamp = dateFormat.format(cur_dt);

    if (ReportsPath == "") { // if results path is passed as null, by
      // default 'C:\' drive is used
      ReportsPath = "C:\\";
    }

    if (ReportsPath.endsWith("\\")) { // checks whether the path ends with
      // '/'
      ReportsPath = ReportsPath + "\\";
    }
    String[] TCNm = scriptName.split("\\.");
    strResultPath = ReportsPath + "/" + TCNm[0] + "/";
    // String htmlname = ReportsPath + "/" + TCNm[0] + "/" + strTimeStamp + ".html";
    detailHTMLReport = ReportsPath + "/" + TCNm[0] + "/" + strTimeStamp + ".html";
    File f = new File(strResultPath);
    f.mkdirs();
    tdrObj.createDetailedRptHeader(TCNm[0]);


    String scriptPath = TestScript + scriptName;
    TScname = scriptName;
    int loopcount = 0;
    int startrow = 0;
    boolean isLoopStmtExist = false;
    FileInputStream fs1 = null;
    WorkbookSettings ws1 = null;
    fs1 = new FileInputStream(new File(scriptPath));
    ws1 = new WorkbookSettings();
    ws1.setLocale(new Locale("en", "EN"));
    Workbook TScworkbook = Workbook.getWorkbook(fs1, ws1);

    // Sheet TScsheet = TScworkbook.getSheet(0); ***Causes null pointer error in ifcondition
    // skipper*****
    TScsheet = TScworkbook.getSheet(0);
    TScrowcount = TScsheet.getRows();
    // *This is the Data Table Sheet-I think its test script sheet-Yuva
    rowcnt = 0;
    // try { //Moving this try below to catch stale exception and continue loop



    keywordScriptForLoop: for (j = 0; j < TScrowcount; j++) {

      // System.out.println("DEBUG:Entering  KeywordScript Loop No-" + j);
      // Thread.sleep(1000);

      rowcnt = rowcnt + 1;
      String TSvalidate = "r";
      if (((TScsheet.getCell(0, j).getContents()).equalsIgnoreCase(TSvalidate) == true)) {
        Action = TScsheet.getCell(1, j).getContents(); // Keyword(B) from test script sheet.
        cCellData = TScsheet.getCell(2, j).getContents(); // Object details(C) from test script
                                                          // sheet.
        dCellData = TScsheet.getCell(3, j).getContents(); // Action (D) from test script sheet.
        eCellData = TScsheet.getCell(4, j).getContents(); // Action2 (E) from test script sheet.
        fCellData = TScsheet.getCell(5, j).getContents(); // Comments (F) from test script sheet.
        String ORPath = ObjectRepository + "OR_SHARED.xls"; // this is shared repopsitory
        String TSORPath = ObjectRepository + ScriptORName; // this is script specific repository
        FileInputStream fs2 = null;
        WorkbookSettings ws2 = null;
        fs2 = new FileInputStream(new File(ORPath));
        ws2 = new WorkbookSettings();
        ws2.setLocale(new Locale("en", "EN"));
        try {
          Workbook ORworkbook = Workbook.getWorkbook(fs2, ws2);
          ORsheet = ORworkbook.getSheet(0);
          ORrowcount = ORsheet.getRows();
          ActionVal = Action.toLowerCase();
          iflag = 0;

        } catch (Exception e) {
          System.out.println(e);
          // fail("Test Script Excel file is not correct.");
        }
        try { // ***Moving this try to before keywordScriptForLoop will terminate loop on exception.
          log("info", "Executing step{" + Action + "}  {" + cCellData + "}  {" + dCellData + "}");
          runTimeValue = "";
          if (fCellData.trim() == "")
            fCellData = agcObj.generateComments(Action, cCellData, dCellData);

          switch (ActionVal) {



            case "loop":
              isLoopStmtExist = true;
              loopnum = 1;
              if (cCellData.trim().equals("")) {
                loopcount = dtObj.getDataTableRowCount();
              } else {
                loopcount = Integer.parseInt(cCellData);
              }

              startrow = j;
              tdrObj.Update_Report("executed");
              // tdrObj.Update_Report("loop" + " Start of loop number" + loopnum);
              tdrObj.Update_Report("loop" + " Starting loop iterations...");
              break;
            case "endloop":
              dtrownum++;
              int loopnumber = loopnum;
              loopcount = loopcount - 1;
              loopnum = loopnum + 1;
              if (loopcount <= 0) {
                System.out.println("Reached End of Loop");
              } else

              {
                j = startrow;
              }
              rowcnt = 1;
              // tdrObj.Update_Report("loop" + " End of loop number" + loopnumber);
              tdrObj.Update_Report("loop" + " Ending loop iteration no:" + loopnumber);
              break;

            case "launchapp":
              if (cCellData.trim().startsWith("http") == false
                  && cCellData.trim().startsWith("file://") == false)
                cCellData = "http://" + cCellData.trim();
              D8.get(cCellData);
              tdrObj.Update_Report("executed");
              break;

            case "wait":
              Thread.sleep(Long.parseLong(cCellData) * 1000);
              // tdrObj.Update_Report("executed");
              break;

            case "waitforpagetoload":
              krfObj.waitForPageToLoad(Integer.parseInt(cCellData));
              tdrObj.Update_Report("executed");
              break;

            case "condition":
              String strConditionStatus = ifcObj.Func_IfCondition(cCellData);
              if (strConditionStatus.equalsIgnoreCase("false")) {
                j = ifcObj.ifContidionSkipper(strConditionStatus);
                // j = j + 1;
                log("info", "Line number from ifcond skipper-" + j);

              }
              tdrObj.Update_Report("executed");
              break;

            case "endcondition":
              tdrObj.Update_Report("executed");
              break;

            case "screencaptureoption":
              String[] sco = cCellData.split(";");

              for (int s = 0; s < sco.length; s++) {
                if (sco[s].equalsIgnoreCase("perform")) {
                  captureperform = true;
                }
                if (sco[s].equalsIgnoreCase("storevalue")) {
                  capturestorevalue = true;
                }
                if (sco[s].equalsIgnoreCase("check")) {
                  capturecheckvalue = true;
                }

              }
              tdrObj.Update_Report("executed");
              break;
            case "importdata":
              /*
               * String xcelpath = cCellData; FileInputStream fs3 = null; WorkbookSettings ws3 =
               * null; fs3 = new FileInputStream(new File(seleniumDir[0].replace("\\", "//") +
               * "//ProjectFramework//TestData//" + xcelpath )); ws3 = new WorkbookSettings();
               * ws3.setLocale(new Locale("en", "EN")); Workbook DTworkbook =
               * Workbook.getWorkbook(fs3, ws3); DTsheet = DTworkbook.getSheet(0); //int DTrowcount
               * = DTsheet.getRows(); DTrowcount = DTsheet.getRows();
               */
              if (!cCellData.trim().endsWith(".xls")) cCellData = cCellData.trim() + ".xls";
              dataTableExcel =
                  seleniumDir[0].replace("\\", "//") + "//ProjectFramework//TestData//"
                      + cCellData.trim();
              dataTableSheet = dCellData.trim();
              tdrObj.Update_Report("executed");
              break;

            case "savedialog":
              Runtime rt = Runtime.getRuntime();
              rt.exec("D://AutoITScript/FileDown.exe");
              break;

            case "connecttodb":
              dbObj.connectToDB(krfObj.getcCellData());
              break;

            case "executesql":
              dbObj.executeQuery(krfObj.getcCellData());
              break;

            case "draganddrop":
              String dragAndDropArgs[] = krfObj.getcCellData().split(";");
              if (dragAndDropArgs.length != 2) throw new Exception("InvalidAgruments");

              String srcObjectNodeAndValue[] =
                  orObj.getObjectNodeAndValue(dragAndDropArgs[0]).split("&&");
              fEObj.Func_FindObj(srcObjectNodeAndValue[0], srcObjectNodeAndValue[1]);
              WebElement srcElement = elem;

              String destObjectNodeAndValue[] =
                  orObj.getObjectNodeAndValue(dragAndDropArgs[1]).split("&&");
              fEObj.Func_FindObj(destObjectNodeAndValue[0], destObjectNodeAndValue[1]);
              WebElement destElement = elem;

              Actions builder = new Actions(D8);
              builder.dragAndDrop(srcElement, destElement).build().perform();
              tdrObj.Update_Report("executed");
              break;

            case "draganddropby":
              String dragAndDropByArgs[] = krfObj.getcCellData().split(";");
              if (dragAndDropByArgs.length != 3) throw new Exception("InvalidAgruments");

              String srcObjectNodeAndValue2[] =
                  orObj.getObjectNodeAndValue(dragAndDropByArgs[0]).split("&&");
              fEObj.Func_FindObj(srcObjectNodeAndValue2[0], srcObjectNodeAndValue2[1]);
              WebElement srcElement2 = elem;

              Actions builder2 = new Actions(D8);
              builder2
                  .dragAndDropBy(srcElement2, Integer.parseInt(dragAndDropByArgs[1]),
                      Integer.parseInt(dragAndDropByArgs[2])).build().perform();
              tdrObj.Update_Report("executed");

              break;

            case "screencapture":
              ssObj.screenshot(loopnum, TScrowcount, TScname);
              tdrObj.Update_Report("executed");
              break;


            case "check":
              scObj.Func_StoreCheck(TSORPath);
              break;

            case "checkpagecontent":

              if (D8.findElement(By.tagName("HTML")).getText().contains(krfObj.getcCellData())) {
                tdrObj.Update_Report("executed");
              }

              else if (D8.findElement(By.xpath("//*[contains(text(), '" + krfObj.getcCellData()
                  + "')]")) != null) {
                tdrObj.Update_Report("executed");
              }

              else {
                tdrObj.Update_Report("failed" + "Prt_Msg"
                    + "Page does not contain the text specified.");
                testStatus = "FAIL";
              }

              break;

            case "storevalue":
              scObj.Func_StoreCheck(TSORPath);
              break;
            case "switchto":
              if (cCellData.trim().equalsIgnoreCase("parentwindow")) {
                log("info", "Driver switched to ParentWindow- "
                    + D8.switchTo().window(parentWindow).getTitle());
              }

              else {
                D8.getWindowHandle();
                Set<String> pops = D8.getWindowHandles();
                log("info", "Window handlers size- " + pops.size());
                Iterator<String> it = pops.iterator();
                while (it.hasNext()) {
                  String popupHandle = it.next().toString();
                  // if(!popupHandle.contains(parent)){
                  log("info",
                      "Driver switched to Pop Up Title- "
                          + D8.switchTo().window(popupHandle).getTitle());
                  // D8.switchTo().window(popupHandle);
                  // System.out.println("DEBUG:Pop Up Title- "+ popupHandle);
                  // }
                }
              }
              // tdrObj.Update_Report("executed");
              break;

            case "sendkeys":
              raObj.robotSendKey(cCellData);
              tdrObj.Update_Report("executed");
              break;

            case "authenticatedialog":
              if (krfObj.isModalDialogShowing()) {
                String credentials[] = cCellData.trim().split("::");
                raObj.copyAndPaste(credentials[0]);
                Thread.sleep(500);
                raObj.robotSendKey("TAB");
                Thread.sleep(500);
                raObj.copyAndPaste(credentials[1]);
                Thread.sleep(500);
                raObj.robotSendKey("ENTER");
                tdrObj.Update_Report("executed");
              } else {
                tdrObj.Update_Report("executed" + "Prt_Msg"
                    + "WARNING! Authentication Dialog was not present.");
              }
              break;

            case "savefileas":
              String fileToSave =
                  seleniumDir[0] + "\\ProjectFramework\\TestData\\" + krfObj.getcCellData();
              mfObj.deleteFileIfExists(fileToSave);

              if (cwpObj.isWindowPresentWithTitle("Opening", 30)) {
                Thread.sleep(1000);
                raObj.robotSendKey("ENTER");
              }

              if (cwpObj.isWindowPresentWithTitle("Enter name of file", 30)) {
                raObj.copyAndPaste(fileToSave);
                Thread.sleep(1000);
                raObj.robotSendKey("ENTER");
              }

              if (dCellData.trim().isEmpty()) {
                // krfObj.isCompletelyDownloaded(fileToSave,5);
                krfObj.isFolderUpdateComplete(seleniumDir[0] + "\\ProjectFramework\\TestData\\", 5);
              } else {
                krfObj.isCompletelyDownloaded(fileToSave, Integer.parseInt(dCellData));
              }

              tdrObj.Update_Report("executed");

              break;

            case "copyandpaste":
              raObj.copyAndPaste(krfObj.getcCellData());

              tdrObj.Update_Report("executed");
              break;

            case "uploadfile":
              // robotSendString(cCellData.trim());
              raObj.copyAndPaste(cCellData.trim());
              raObj.robotSendKey("enter");
              tdrObj.Update_Report("executed");
              break;

            case "runprogram":
              Runtime icR = Runtime.getRuntime();
              icR.exec(cCellData.trim());
              break;

            case "mousehovermenu":

              String[] menuItems = cCellData.split(">>");
              log("info", "Mouse hover menu items count:-" + menuItems.length);
              Actions actions = new Actions(D8);
              WebElement tempElem;
              for (int i = 0; i < menuItems.length; i++) {
                // tempElem = D8.findElement(By.linkText(menuItems[i].trim()));
                tempElem =
                    new WebDriverWait(D8, 5).until(ExpectedConditions.visibilityOfElementLocated(By
                        .linkText(menuItems[i].trim())));
                // tempElem = new WebDriverWait(D8,
                // 5).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[text()='" +
                // menuItems[i].trim() + "']")));
                actions.moveToElement(tempElem).build().perform();
                // actions.moveToElement(tempElem).build();

              }
              actions.click();
              actions.perform();

              tdrObj.Update_Report("executed");
              break;

            case "switchtoframe":
              WebDriverWait waitForFrame =
                  new WebDriverWait(D8, Integer.parseInt(dCellData.trim()));
              waitForFrame.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(cCellData
                  .trim()));
              // tdrObj.Update_Report("executed");
              break;

            case "m.perform":
              if (automationEnvironment.equalsIgnoreCase("Appium")) {
                mgaObj.executeMobileGesturesInAppium();
                tdrObj.Update_Report("executed");

              } else if ((automationEnvironment.equalsIgnoreCase("Selendroid"))) {
                mgsObj.executeMobileGesturesInSelendroid();
                tdrObj.Update_Report("executed");
              } else {
                log("info", "WARNING! This keyword is only for Mobile Testing.Skipping Step");
              }
              break;

            case "perform":
              String ObjectVal = "";
              if (cCellData.split(";").length == 0) {
                ObjectVal = cCellData.trim();
              } else {
                String[] cCellDataVal = cCellData.split(";");
                // String ObjectVal = cCellData.substring(cCellDataVal[0].length() +
                // 1,cCellData.length());
                ObjectVal = cCellDataVal[1].trim();
              }

              String[] dCellDataVal = dCellData.split(":");
              String ObjectSet = dCellDataVal[0].toLowerCase();
              String ObjectSetVal = "";

              /*
               * if(dCellData.contains("dt_")){ DTcolumncount = 0; DTcolumncount =
               * DTsheet.getColumns(); }
               */

              if (dCellDataVal.length == 2) {

                ObjectSetVal = dCellDataVal[1];
              }


              String getObjectLocatorString = orObj.getObjectLocator(ObjectVal);

              if (getObjectLocatorString == null) {

                throw new Exception("ObjectLocatorNotFoundInOR");
              } else {

                if (getObjectLocatorString.contains("==") == false) {
                  throw new Exception("SyntaxErrorInORLocator");
                }

                String[] objectLocatorDetails = getObjectLocatorString.split("==");
                ORvalname = objectLocatorDetails[0];
                ORvalue = objectLocatorDetails[1];
              }

              switch (ObjectSet) {

                case "set":
                  wfeObj.waitTillVisible("60");
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("$")) {
                    ObjectSetVal = dtfObj.getSystemVariable(ObjectSetVal.trim());
                  }
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("#")) {
                    ObjectSetVal = map.get(ObjectSetVal.substring(1, (ObjectSetVal.length())));
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("dt_")) {
                    ObjectSetVal = dtObj.getDataTableValue(ObjectSetVal, dtrownum);
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("db_")) {
                    ObjectSetVal =
                        DBResultSet2D.get(ObjectSetVal.substring(3, (ObjectSetVal.length())));
                  }

                  runTimeValue = ObjectSetVal;
                  /*
                   * String ObjectSetValtableheader[] = ObjectSetVal .split("_"); int column = 0;
                   * String Searchtext = ObjectSetValtableheader[1]; for (column = 0; column <
                   * DTcolumncount; column++) { if (Searchtext.equalsIgnoreCase(DTsheet
                   * .getCell(column, 0).getContents()) == true) { ObjectSetVal =
                   * DTsheet.getCell(column, dtrownum).getContents(); iflag = 1; }
                   * 
                   * } if (iflag == 0) { ORvalname = "exit"; } }
                   */


                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  // elem.focus();
                  // elem.clear();
                  elem.sendKeys(ObjectSetVal);
                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }

                  break;

                case "listselect":
                  wfeObj.waitTillClickable("60");
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("dt_")) {
                    ObjectSetVal = dtObj.getDataTableValue(ObjectSetVal, dtrownum);
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("db_")) {
                    ObjectSetVal =
                        DBResultSet2D.get(ObjectSetVal.substring(3, (ObjectSetVal.length())));
                  }
                  runTimeValue = ObjectSetVal;
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  String[] listvalues = ObjectSetVal.split(",");

                  List<WebElement> listboxitems = elem.findElements(By.tagName("option"));
                  Select chooseoptn = new Select(elem);
                  chooseoptn.deselectAll();
                  for (WebElement opt : listboxitems) { // System.out.println(opt.getText());
                    for (int i = 0; i < listvalues.length; i++) {
                      if (opt.getText().equalsIgnoreCase(listvalues[i])) {
                        // System.out.println(listvalues[i]);
                        chooseoptn.selectByVisibleText(opt.getText());
                      }
                    }
                  }

                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }

                  break;

                case "select":
                  wfeObj.waitTillClickable("60");
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("$")) {
                    ObjectSetVal = dtfObj.getSystemVariable(ObjectSetVal.trim());
                  }
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("#")) {
                    ObjectSetVal = map.get(ObjectSetVal.substring(1, (ObjectSetVal.length())));
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("dt_")) {
                    ObjectSetVal = dtObj.getDataTableValue(ObjectSetVal, dtrownum);
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("db_")) {
                    ObjectSetVal =
                        DBResultSet2D.get(ObjectSetVal.substring(3, (ObjectSetVal.length())));
                  }

                  /*
                   * if (ObjectSetVal.contains("dt_")) { String ObjectSetValtableheader[] =
                   * ObjectSetVal .split("_"); int column = 0; String Searchtext =
                   * ObjectSetValtableheader[1];
                   * 
                   * for (column = 0; column < DTcolumncount; column++) { if
                   * (Searchtext.equalsIgnoreCase(DTsheet .getCell(column, 0).getContents()) ==
                   * true) { ObjectSetVal = DTsheet.getCell(column, dtrownum).getContents(); iflag =
                   * 1; }
                   * 
                   * } if (iflag == 0) { ORvalname = "exit"; } }
                   */
                  runTimeValue = ObjectSetVal;
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  new Select(elem).selectByVisibleText(ObjectSetVal);
                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }

                  break;

                case "check":
                  wfeObj.waitTillClickable("60");
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("$")) {
                    ObjectSetVal = dtfObj.getSystemVariable(ObjectSetVal.trim());
                  }
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("#")) {
                    ObjectSetVal = map.get(ObjectSetVal.substring(1, (ObjectSetVal.length())));
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("dt_")) {
                    ObjectSetVal = dtObj.getDataTableValue(ObjectSetVal, dtrownum);
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("db_")) {
                    ObjectSetVal =
                        DBResultSet2D.get(ObjectSetVal.substring(3, (ObjectSetVal.length())));
                  }

                  /*
                   * if (ObjectSetVal.contains("dt_")) { String ObjectSetValtableheader[] =
                   * ObjectSetVal .split("_"); int column = 0; String Searchtext =
                   * ObjectSetValtableheader[1]; for (column = 0; column < DTcolumncount; column++)
                   * { if (Searchtext.equalsIgnoreCase(DTsheet .getCell(column, 0).getContents()) ==
                   * true) { ObjectSetVal = DTsheet.getCell(column, dtrownum).getContents(); iflag =
                   * 1; } } if (iflag == 0) { ORvalname = "exit"; } }
                   */
                  runTimeValue = ObjectSetVal;
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  if (elem.isSelected() && dCellDataVal[1].equalsIgnoreCase("On")) {

                  } else if (elem.isSelected() || dCellDataVal[1].equalsIgnoreCase("On")) {
                    elem.click();
                  }
                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "attachfile":
                  if (ObjectSetVal.substring(0, 1).equalsIgnoreCase("#")) {
                    ObjectSetVal = map.get(ObjectSetVal.substring(1, (ObjectSetVal.length())));
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("dt_")) {
                    ObjectSetVal = dtObj.getDataTableValue(ObjectSetVal, dtrownum);
                  }
                  if (ObjectSetVal.substring(0, 3).equalsIgnoreCase("db_")) {
                    ObjectSetVal =
                        DBResultSet2D.get(ObjectSetVal.substring(3, (ObjectSetVal.length())));
                  }

                  runTimeValue = ObjectSetVal;
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  // Concatenate the full path with filename
                  ObjectSetVal = seleniumDir[0] + "\\ProjectFramework\\TestData\\" + ObjectSetVal;
                  log("info", "Attaching file-" + ObjectSetVal);
                  elem.sendKeys(ObjectSetVal);

                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "click":
                  wfeObj.waitTillClickable("60");
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  elem.click();

                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "clear":
                  wfeObj.waitTillVisible("60");
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  elem.clear();

                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "submit":
                  wfeObj.waitTillClickable("60");
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  elem.submit();

                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "enter":
                  fEObj.Func_FindObj(ORvalname, ORvalue);
                  elem.sendKeys("\n");

                  tdrObj.Update_Report("executed");
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "waittillclickable":

                  WebElement elementClickable = null;

                  if (ORvalname.equalsIgnoreCase("id")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.id(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("name")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.name(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("xpath")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.xpath(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("link")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.linkText(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("partiallink")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By
                                .partialLinkText(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("css")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.cssSelector(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("class")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.className(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("tag")) {
                    elementClickable =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.elementToBeClickable(By.tagName(ORvalue)));
                  }



                  if (elementClickable != null) {
                    tdrObj.Update_Report("executed");
                  } else {
                    testStatus = "FAIL";
                    tdrObj.Update_Report("failed" + "Prt_Msg"
                        + "Element was not clickable till the specified time.");

                  }
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "waittillvisible":

                  WebElement elementVisible = null;


                  if (ORvalname.equalsIgnoreCase("id")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By.id(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("name")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By.name(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("xpath")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("link")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By
                                .linkText(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("partiallink")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By
                                .partialLinkText(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("css")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By
                                .cssSelector(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("class")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By
                                .className(ORvalue)));
                  } else if (ORvalname.equalsIgnoreCase("tag")) {
                    elementVisible =
                        new WebDriverWait(D8, Integer.parseInt(ObjectSetVal))
                            .until(ExpectedConditions.visibilityOfElementLocated(By
                                .tagName(ORvalue)));
                  }



                  if (elementVisible != null) {
                    tdrObj.Update_Report("executed");
                  } else {
                    testStatus = "FAIL";
                    tdrObj.Update_Report("failed" + "Prt_Msg"
                        + "Element was not visible till the specified time.");

                  }
                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "alert":
                  try {
                    Alert alert = D8.switchTo().alert();
                    String actualAlertMsg = alert.getText();
                    if (dCellDataVal[1].equalsIgnoreCase("ok")
                        && actualAlertMsg.contains(ObjectVal) == true) {
                      alert.accept();
                      tdrObj.Update_Report("executed");
                    }
                    if (dCellDataVal[1].equalsIgnoreCase("cancel")
                        && actualAlertMsg.contains(ObjectVal) == true) {
                      alert.dismiss();
                      tdrObj.Update_Report("executed");
                    }

                    if (dCellDataVal[1].equalsIgnoreCase("ok")
                        && actualAlertMsg.contains(ObjectVal) == false) {
                      alert.accept();
                      tdrObj.Update_Report("failed" + "Prt_Msg" + "Actual Alert text is:"
                          + actualAlertMsg);
                      testStatus = "FAIL";
                    }
                    if (dCellDataVal[1].equalsIgnoreCase("cancel")
                        && actualAlertMsg.contains(ObjectVal) == false) {
                      alert.dismiss();
                      tdrObj.Update_Report("failed" + "Prt_Msg" + "Actual Alert text is:"
                          + actualAlertMsg);
                      testStatus = "FAIL";
                    }

                  } catch (NoAlertPresentException ex) {
                    tdrObj.Update_Report("failed" + "Prt_Msg" + "No Such Alert Present");
                    testStatus = "FAIL";
                    // No alert present
                  }

                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

                case "frame":
                  try {
                    if (dCellDataVal[1].equalsIgnoreCase("switchto")) {
                      fEObj.Func_FindObj(ORvalname, ORvalue);
                      D8.switchTo().frame(elem);
                      tdrObj.Update_Report("executed");
                    }
                    if (dCellDataVal[1].equalsIgnoreCase("switchfrom")) {
                      // D8.switchTo().defaultContent;
                      tdrObj.Update_Report("executed");
                    }

                  } catch (Exception ex) {
                    tdrObj.Update_Report("failed" + "Prt_Msg" + "No Such Frame Present");
                    testStatus = "FAIL";
                    // No Frame present
                  }

                  if (captureperform == true) {
                    ssObj.screenshot(loopnum, TScrowcount, TScname);
                  }
                  break;

              }// End of Objectset Switch
               // tdrObj.Update_Report("executed");
              break;

            default:
              tdrObj.Update_Report("skipped");
              break;
          }// End of Actval Switch
           // }// End of IF loop
           // }// End of For loop that get all rows in Test Script
           // bw.close(); //moving close to just below after completing header write in case of
           // exception.-Yuva

        } catch (StaleElementReferenceException e) {
          log("error", "Stale Element exception Caught in Execute keyword Script.");
          // staleElemChecker = j;

          if (staleElemExCtr > 5) {
            log("error", "Stale Element exception exceeded retry limit.Ending keyword Script.");
            errorDesc = cemObj.getErrorDescription(e.getMessage());
            tdrObj.Update_Report("failed");
            testStatus = "FAIL";
            log("info",
                "Updating summary report [StaleElementReferenceException catch block] with test status as: "
                    + testStatus);
            tsrObj.updateSummaryReport(scriptName, "failed");
            bw.close();
            testStatus = "SKIP_SUMMARYREPORT_UPDATE";
            break keywordScriptForLoop;

            // Throw an exception to halt the script.
            // throw("Stale Element Exception Caught");
          }

          else {
            // Just update the for loop counter to retry.
            j--;
            staleElemExCtr++;
          }

          // System.out.println(e);
          // System.out.println("Because of specification of SeleniumWebDriver, downloading may be failed.");
          // System.out.println("Please confirm the report file and screenshot about test result.");
        } catch (Exception ex) {
          if (ActionVal.equalsIgnoreCase("checkPageContent")) {
            errorDesc = cemObj.getErrorDescription("ContentNotFoundInPage");
          } else {
            errorDesc = cemObj.getErrorDescription(ex.getMessage());

          }
          tdrObj.Update_Report("failed");

          if (isLoopStmtExist == true && loopcount > 0) {
            // Do not break the loop-keyword.. continue the loop till it ends.
            log("info", "Catching exception with Loop count as:" + loopcount);

            dtrownum++;
            int loopnumber = loopnum;
            loopcount = loopcount - 1;
            // loopnum = loopnum + 1;


            if (loopcount == 0) {
              log("info", "Reached End of Loop @ keyword script catch exception");
              log("info",
                  "Getting the row no of Endloop keyword with para{" + j + "}:"
                      + krfObj.getEndLoopRowNo(j));
              j = krfObj.getEndLoopRowNo(j);
            }

            else {
              loopnum = loopnum + 1;
              j = startrow;
              rowcnt = 1;
              tdrObj.Update_Report("loop: A Step failed during loop no- " + loopnumber
                  + ".Skipping remaining steps of loop.");
            }


          } else {
            testStatus = "FAIL";
            log("info",
                "Updating summary report [execute keyword script catch] with test status as: "
                    + testStatus);
            tsrObj.updateSummaryReport(scriptName, "failed");
            bw.close();
            // bwSummaryRpt.close();

            log("error", "Exception Caught in Execute keyword Script: " + ex.getMessage());


            testStatus = "SKIP_SUMMARYREPORT_UPDATE";
            break keywordScriptForLoop;
          }



        }
      }// End of IF loop
    }// End of For loop that get all rows in Test Script
    bw.close(); // moving close to just below after completing header write in case of
                // exception.-Yuva

  }// End of Function


}
